package com.study.handler;

import java.util.List;
import com.study.enums.HttpStatusEnum;
import com.study.utils.mybatisplus.ErrorCodeException;
import com.study.result.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.ObjectError;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * 通用标准的RestController错误拦截处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = NoHandlerFoundException.class)
    public AjaxResult handle(NoHandlerFoundException e) {
        log.info("NoHandlerFoundException ===> " + e);
        return AjaxResult.fail(HttpStatusEnum.NOT_FOUND.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = {DataIntegrityViolationException.class, MyBatisSystemException.class})
    public AjaxResult handle(DataAccessException e) {
        log.info("DataAccessException ===> " + e);
        return AjaxResult.fail(HttpStatusEnum.SERVER_ERROR.getCode(), HttpStatusEnum.SERVER_ERROR.getMsg());
    }

    @ExceptionHandler(value = ErrorCodeException.class)
    public AjaxResult handle(ErrorCodeException e) {
        log.info("ErrorCodeException ===> " + e);
        return AjaxResult.fail(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handle(MethodArgumentNotValidException e){
        log.info("ParamNotValidException ===> " + e);
        List<ObjectError> errorList = e.getAllErrors();
        StringBuilder errorMessage = new StringBuilder();
        for (ObjectError error : errorList) {
            errorMessage.append(error.getDefaultMessage()).append("。");
        }
        return AjaxResult.fail(HttpStatusEnum.INVALID_PARAMETER.getCode(), errorMessage.toString());
    }

    @ExceptionHandler(value = Exception.class)
    public AjaxResult defaultErrorHandler(Exception e) {
        log.info("Exception ===> " + e);
        return AjaxResult.fail(HttpStatusEnum.ERROR.getCode(), e.getMessage().replace("com.study.", ""));
    }

}
